package com.qlylkj.lbk.app

import com.forest.core.util.Preference
import com.google.gson.Gson
import com.qlylkj.lbk.model.bean.User
import com.qlylkj.lbk.model.bean.UserInfo

object PreferenceHelper {

    var hasNetwork: Boolean by Preference(Constant.NetWork.HAS_NETWORK_KEY, true)

    var isLogin: Boolean by Preference(Constant.User.IS_LOGIN_KEY, false)

    var messageNotificationSwitch: Boolean by Preference(Constant.User.IS_LOGIN_KEY, true)

    var token: String by Preference(Constant.User.TOKEN_KEY, "")

    var userId: String by Preference(Constant.User.USER_ID_KEY, "")

    private var userInfoString: String by Preference(Constant.User.USER_INFO_KEY, "")

    fun setUser(user: User){
        isLogin = true
        token = user.token
        setUserInfo(user.userInfo)
    }

    fun setUserInfo(userInfo: UserInfo){
        userInfo.apply {
            userId = id
        }
        userInfoString = Gson().toJson(userInfo)
    }

    fun getUserInfo(success: (UserInfo) -> Unit = {}, failed: () -> Unit = {}){
        if (isLogin && userInfoString.isNotEmpty()) {
            success(Gson().fromJson(userInfoString, UserInfo::class.java))
        } else {
            failed()
        }
    }

    fun logout(){
        isLogin = false
        token = ""
        userId = ""
        userInfoString = ""
    }
}